package org.jeecg.config.wlhy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import org.jeecg.common.constant.enums.AmapErrorCode;
import org.jeecg.common.constant.enums.BaiduErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

import static org.jeecg.config.wlhy.OkHttp.HTTP_CLIENT;

@Configuration
@Slf4j
public class AmapClient {

    @Value("${amap.key}")
    private String key;

    @Value("${amap.sig}")
    private String sig;

    /**
     * 地理编码
     *
     * @param address 规则遵循：国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦，如：北京市朝阳区阜通东大街6号。
     * @param city    可选输入内容包括：指定城市的中文（如北京）、指定城市的中文全拼（beijing）、citycode（010）、adcode（110000），不支持县级市。当指定城市查询内容为空时，会进行全国范围内的地址转换检索。
     *                <p>
     *                adcode信息可参考城市编码表获取
     * @return
     * @throws IOException
     */

    public JSONArray geocodeGeo(String address, String city) throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse("https://restapi.amap.com/v3/geocode/geo").newBuilder();
        urlBuilder.addQueryParameter("key", key);
        urlBuilder.addQueryParameter("address", address);
        urlBuilder.addQueryParameter("city", city);
        String url = urlBuilder.build().toString();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null) // 不带请求体
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if ("1".equals(jsonObject.getString("status"))) {
            return jsonObject.getJSONArray("geocodes");
        }
        AmapErrorCode errorCode = AmapErrorCode.getInstance(jsonObject.getInteger("infocode"));
        throw new RuntimeException(errorCode.getMessage());
    }

    public JSONObject ip(String ip) throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse("https://restapi.amap.com/v3/ip").newBuilder();
        urlBuilder.addQueryParameter("key", key);
        urlBuilder.addQueryParameter("ip", ip);

        String url = urlBuilder.build().toString();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null) // 不带请求体
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if ("1".equals(jsonObject.getString("status"))) {
            return jsonObject;
        }
        AmapErrorCode errorCode = AmapErrorCode.getInstance(jsonObject.getInteger("infocode"));
        throw new RuntimeException(errorCode.getMessage());
    }


}
